package com.offcn.web.servlet;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.Course;
import com.offcn.entity.Paging;
import com.offcn.entity.ResultVo;
import com.offcn.service.impl.CourseServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@WebServlet("/course")
@MultipartConfig
public class CourseServlet extends BaseServlet {
    private CourseServiceImpl service = new CourseServiceImpl();
    private ResultVo resultVo;
    //查询课程分页展示的方法
    public void findCourseByPage(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        //1.查数据库中course表中的总条数
        String searchCourse = req.getParameter("searchCourse");
        int count = service.queryAllCount(searchCourse);
        //将总条数，每页显示的条数，当前页等数据传进Paging协助类，计算得到分页所需要的全部数据
        String pageSize = req.getParameter("pageSize");
        String currentPage = req.getParameter("currentPage");
        Paging<Course> page = new Paging<Course>(currentPage, Integer.parseInt(pageSize),count);
        //2.再次查询数据库
        List<Course> list = service.findCourseByPage(page,searchCourse);
        //3.将list也封装进paging协助类中，因为向页面响应时只能是一个整体，所以必须将list也添加进paging类
        page.setList(list);
        //判断
        if (page.getList() != null && page.getList().size() > 0){
            resultVo = new ResultVo(1, "查询成功！", page);
        }else {
            resultVo = new ResultVo(0, "查询失败！", page);
        }
        String s = JSON.toJSONString(resultVo);
        resp.getWriter().print(s);
    }
    //删除的方法
    public void deleteAccordingSelection(HttpServletRequest req,HttpServletResponse resp) throws IOException, SQLException {
        String delarr = req.getParameter("delarr");
        int row = service.deleteAccordingSelection(delarr);
        if (row > 0){
            resultVo = new ResultVo(1, "删除成功！", row);
        }else {
            resultVo = new ResultVo(0, "删除失败！", row);
        }
        String s = JSON.toJSONString(resultVo);
        resp.getWriter().print(s);
    }

    //上传文件
    public void uploadFile(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
        Part part = req.getPart("file");
        String fileName = part.getSubmittedFileName();
        fileName = UUID.randomUUID() + fileName;
        String path = "C:\\Users\\Administrator\\Desktop\\file\\";
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        part.write(path + fileName);
    }
}
